<template>
  <div class="app-container">
    <el-card class="infobox" :top="20">
      <div class="title">账号设置</div>
      <div class="formbox pageForm">
        <el-form
          @submit.native.prevent
          ref="form"
          :model="user"
          :rules="rules"
          label-width="112px"
        >
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-if="!showEdit"
              style="width: 320px"
              v-model="user.nickName"
              maxlength="30"
            />
            <div v-else>{{ user.nickName }}</div>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group
              v-removeAriaHidden
              v-if="!showEdit"
              v-model="user.sex"
            >
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
            <div v-else>
              {{ user.sex == 1 ? '女' : '男' }}
            </div>
          </el-form-item>
          <el-form-item label="个人头像">
            <div class="flex">
              <userAvatar
                :showEdit="showEdit"
                :user="user"
                @refresh="AvatarReturn"
              />
              <div class="avatarTip">
                建议图片比例为 1:1 或 160 *
                160px，支持JPG、PNG格式，图片小于5M。
              </div>
            </div>
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber">
            <div class="flex">
              <div>{{ user.phoneNumber | regPhone }}</div>
              <el-link
                @click="handleClick"
                :underline="false"
                v-if="!showEdit"
                style="margin-left: 16px"
                type="primary"
              >更换手机号
              </el-link
              >
            </div>
          </el-form-item>
          <div class="flex" style="margin: 40px 0 0 114px">
            <el-button v-if="!showEdit" @click="showEdit = true"
            >取 消
            </el-button
            >
            <el-button
              v-if="!showEdit"
              style="margin-left: 32px"
              type="primary"
              @click="submit"
            >保 存
            </el-button
            >
            <el-button v-if="showEdit" type="primary" @click="showEdit = false"
            >编 辑
            </el-button
            >
          </div>
        </el-form>
      </div>
    </el-card>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="`${user.phoneNumber ? '更换手机号码' : '绑定手机号码'}`"
      @close="cancel"
      :visible.sync="showDialog"
      width="500px"
    >
      <!-- 重置密码 -->
      <div class="content">
        <el-form
          class="login_form"
          ref="phoneLoginForm"
          :model="phoneLoginForm"
          :rules="phoneLoginRules"
        >
          <el-form-item prop="username">
            <el-input
              class="form_ipt"
              v-model="phoneLoginForm.username"
              type="text"
              auto-complete="off"
              :placeholder="`${
                user.phoneNumber ? '请输入将要更换的手机号码' : '请输入手机号码'
              }`"
            >
              <img
                slot="prefix"
                class="ipt_icon"
                src="@/assets/images/ipt_user_icon.png"
                alt="加载失败"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              oninput="value=value.replace(/^-1|[^0-9]/g,'')"
              maxlength="6"
              class="form_ipt"
              v-model="phoneLoginForm.code"
              type="text"
              auto-complete="off"
              placeholder="请输入验证码"
              @keyup.enter.native="handleReset"
            >
              <img
                slot="prefix"
                class="ipt_icon"
                src="@/assets/images/code_icon.png"
                alt="加载失败"
              />
              <div
                class="get_code"
                slot="suffix"
                @click="getVerCode"
                v-if="ifSend"
              >
                {{ ifFistClick ? '获取验证码' : '重新获取' }}
              </div>
              <div class="get_code" slot="suffix" v-else>{{ second }}S</div>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="login_btn"
              :class="{
                opacity: !phoneLoginForm.username || !phoneLoginForm.code,
              }"
              :loading="loading"
              size="medium"
              type="primary"
              @click.native.prevent="handleReset"
            >
              <span class="font_bold" v-if="!loading">确 认</span>
              <span class="font_bold" v-else>确 认 中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userAvatar from './userAvatar'
import { checkPhone } from '@/utils/validate'
import { sendPhoneCodeForUpdatePhone, changePhone } from '@/api/login'
import { getUserProfile, updateUserProfile } from '@/api/system/user'

export default {
  name: 'Profile',
  components: { userAvatar },
  data() {
    return {
      user: {},
      showEdit: true,
      showDialog: false,
      loading: false,
      ifSend: true,
      ifFistClick: true,
      second: '',
      //手机号重置密码
      phoneLoginForm: {
        username: '',
        code: '',
        newPassword: '',
        againPassword: ''
      },
      phoneLoginRules: {
        username: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        code: [{ required: true, trigger: 'blur', message: '请输入验证码' }]
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUser()
  },
  methods: {
    handleClick() {
      this.showDialog = true
    },
    // 重置密码确认
    handleReset() {
      this.$refs.phoneLoginForm.validate(async(valid) => {
        if (valid) {
          this.loading = true
          let params = {
            phone: this.phoneLoginForm.username,
            phoneCode: this.phoneLoginForm.code,
            userId: this.$store.getters.userId
          }
          let res
          try {
            res = await changePhone(params)
            // 重置密码成功
            if (res.code == 200) {
              this.$modal.msgSuccess('手机号绑定成功')
            }
          } finally {
            this.loading = false
          }
        }
      })
    },
    async getVerCode() {
      if (!this.phoneLoginForm.username) {
        this.$modal.msgWarning('请输入手机号')
        return
      }
      if (
        !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
          this.phoneLoginForm.username
        )
      ) {
        this.$modal.msgWarning('请输入正确的手机号')
        return
      }
      if (!this.ifSend) {
        return
      }
      let res = await sendPhoneCodeForUpdatePhone({
        phone: this.phoneLoginForm.username
      })
      if (res.code == 200) {
        this.$modal.notifySuccess('验证码发送成功')
        this.ifFistClick = false
        this.second = 59
        this.ifSend = false
        let time = null
        clearInterval(time)
        time = setInterval(() => {
          if (this.second > 0) {
            this.second--
          } else {
            clearInterval(time)
            this.ifSend = true
          }
        }, 1000)
      }
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理…',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.3)'
          })
          updateUserProfile(this.user)
            .then(() => {
              loading.close()
              this.$modal.msgSuccess('修改成功')
              this.$store.commit('SET_AVATAR', this.user.avatar)
              this.$store.commit('SET_NAME', this.user.nickName)
              setTimeout(() => {
                this.$router.go(-1)
              }, 1000)
            })
            .catch(() => {
              loading.close()
            })
        }
      })
    },
    getUser() {
      getUserProfile().then((response) => {
        this.user = response.data
        this.user.avatar =
          this.user.avatar == '' || this.user.avatar == null
            ? this.$store.getters.avatar
            : this.user.avatar
        console.log(response.data, 'response')
      })
    },
    cancel() {
      this.resetForm('phoneLoginForm')
      this.showDialog = false
    },
    AvatarReturn(e) {
      this.user.avatar = e
    }
  }
}
</script>
<style lang="scss" scoped>
.infobox {
  .title {
    padding: 32px 0 0 40px;
    font-size: 18px;
    font-family: PingFangSC-Semibold, PingFang SC, sans-serif;
    font-weight: 600;
    color: #333333;
    line-height: 25px;
  }

  .formbox {
    padding: 32px 0 0 211px;
  }

  .pageForm {
    display: flex;
    justify-content: center;
  }

  .avatarTip {
    margin-left: 10px;
    height: 80px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    color: #a3a3a3;
    line-height: 140px;
  }

  .reset {
    margin-left: 18px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    color: #28b28b;
  }
}

.content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;

  .change_sussess_icon {
    width: 95px;
    height: 92px;
  }

  .sign_txt {
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    line-height: 22px;
    margin: 32px 0 54px;
  }

  .route_btn {
    margin-top: 23px;
    width: 360px !important;
    height: 48px;
    border-radius: 30px;
    margin-bottom: 32px;
  }

  .login_form {
    ::v-deep .form_ipt.el-input--medium .el-input__inner {
      width: 360px;
      height: 48px;
      background: #ffffff;
      border-radius: 30px;
      line-height: 48px;
      padding-left: 62px;
      box-sizing: border-box;
    }

    ::v-deep .el-input__prefix {
      margin-top: 14px;
      left: 32px;
    }

    .forget_pws {
      color: #999999;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 14px;
      display: flex;
      justify-content: flex-end;
      cursor: pointer;
      user-select: none;
      margin-top: -10px;

      &:hover {
        color: #1b64ff;
      }
    }

    .login_btn {
      //margin-top: 23px;
      width: 360px !important;
      height: 48px;
      border-radius: 30px;
    }

    .opacity {
      opacity: 0.28;
    }
  }

  .sign {
    margin-top: 20px;
    width: 100%;
    border-top: 2px solid #efeff2;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    box-sizing: border-box;

    .text {
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 14px;
      color: #f89a33;
      line-height: 20px;
    }
  }
}

.ipt_icon {
  width: 19px;
  height: 20px;
  margin-bottom: 3px;
}

.get_code {
  cursor: pointer;
  user-select: none;
  color: #28b28b;
  margin: 6px 16px 0 0;
}
</style>
